#include "stm32f10x.h"

void Pwm_Init(void)
{
    // enable rcc-tim2 
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

    // enable rcc-gpioa
    // init output gpio pin
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
    GPIO_InitTypeDef GPIO_InitParam;
    GPIO_InitParam.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitParam.GPIO_Pin = GPIO_Pin_0;
    GPIO_InitParam.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitParam);

    // select clock input mode
    TIM_InternalClockConfig(TIM2);

    // configure base-time unit
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitParam;
    TIM_TimeBaseInitParam.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInitParam.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInitParam.TIM_Period = 100 - 1;
    TIM_TimeBaseInitParam.TIM_Prescaler = 720 - 1; // 72 * 1000 * 1000
    TIM_TimeBaseInitParam.TIM_RepetitionCounter = 0;
    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitParam);

    // configure output compare
    // configure output polarity
    TIM_OCInitTypeDef TIM_OCInitParam;
    TIM_OCStructInit(&TIM_OCInitParam);
    TIM_OCInitParam.TIM_OCMode = TIM_OCMode_PWM1;
    TIM_OCInitParam.TIM_OCPolarity = TIM_OCPolarity_High;
    TIM_OCInitParam.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitParam.TIM_Pulse = 1;
    TIM_OC1Init(TIM2,  &TIM_OCInitParam);

    // enable tim
    TIM_Cmd(TIM2, ENABLE);
    

}

void Pwm_setCompare1(uint8_t compare)
{
    TIM_SetCompare1(TIM2, compare);
}